package util;

/**
 * @program: java_concurrent
 * @description: 平均误差，平均相对误差，平均相对误差，均方误差，均方根误差
 * @author: lxf
 * @create: 2024-07-22 14:25
 **/
public class MathUtil {

    private static double formatDouble(double num) {
        return Double.parseDouble(String.format("%.2f", num));
    }

    /*
    * 平均误差 (Mean Error, ME)
    * */
    public static double meanError(double[] actual, double[] predicted) {
        double sum = 0;
        for (int i = 0; i < actual.length; i++) {
            sum += actual[i] - predicted[i];
        }
        return formatDouble(sum / actual.length);
    }

    /*
     * 平均相对误差 (Mean Relative Error, MRE)
     * */
    public static double meanRelativeError(double[] actual, double[] predicted) {
        double sum = 0;
        for (int i = 0; i < actual.length; i++) {
            sum += Math.abs(actual[i] - predicted[i]) / actual[i];
        }
        return formatDouble(sum / actual.length);
    }

    /*
     * 平均绝对误差 (Mean Absolute Error, MAE)
     * */
    public static double meanAbsoluteError(double[] actual, double[] predicted) {
        double sum = 0;
        for (int i = 0; i < actual.length; i++) {
            sum += Math.abs(actual[i] - predicted[i]);
        }
        return formatDouble(sum / actual.length);
    }

    /*
     * 均方误差 (Mean Squared Error, MSE)
     * */
    public static double meanSquaredError(double[] actual, double[] predicted) {
        double sum = 0;
        for (int i = 0; i < actual.length; i++) {
            sum += Math.pow(actual[i] - predicted[i], 2);
        }
        return formatDouble(sum / actual.length);
    }

    /*
     * 均方根误差 (Root Mean Squared Error, RMSE)
     * */
    public static double rootMeanSquaredError(double[] actual, double[] predicted) {
        return formatDouble(Math.sqrt(meanSquaredError(actual, predicted)));
    }
}
